//https://leetcode.cn/problems/unique-paths-iii/
class Solution {
    int[] dx;
    int[] dy;
    boolean[][] check;
    int m, n;
    int ret;//返回值
    int count;//所有的0的个数
    public int uniquePathsIII(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        int inX = 0;
        int inY = 0;
        check = new boolean[m][n];
        dx = new int[]{-1, 1, 0, 0};
        dy = new int[]{0, 0, -1, 1};
        for(int i = 0; i < m; i++)
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 0) count++;
                if(grid[i][j] == 1) {
                    inX = i;
                    inY = j;
                }
            }
        check[inX][inY] = true;
        dfs(grid, inX, inY, 0);
        return ret;
    }
    public void dfs(int[][] grid, int i, int j, int count0) {
        if(grid[i][j] == 2) {
            if(count0 == count) ret++;
            return;
        }
        //每个格子的上下左右都要穷举
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && check[x][y] == false && grid[x][y] != -1) {
                check[x][y] = true;
                if(grid[x][y] == 0) count0++;//可能这个位置是2
                dfs(grid, x, y, count0);
                //回溯
                if(grid[x][y] == 0) count0--;
                check[x][y] = false;
            }
        }
    }
}